{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d566cc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from tqdm.notebook import tqdm\n",
    "import benchmark\n",
    "import utils\n",
    "from openai_cache import Completion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bdaedc66",
   "metadata": {},
   "outputs": [],
   "source": [
    "def construct_placement_prompt(summary, objects, receptacles):\n",
    "    placement_prompt_template = '''# Summary: Put clothes in the laundry basket and toys in the storage box.\n",
    "objects = [\"socks\", \"toy car\", \"shirt\", \"Lego brick\"]\n",
    "receptacles = [\"laundry basket\", \"storage box\"]\n",
    "pick_and_place(\"socks\", \"laundry basket\")\n",
    "pick_and_place(\"toy car\", \"storage box\")\n",
    "pick_and_place(\"shirt\", \"laundry basket\")\n",
    "pick_and_place(\"Lego brick\", \"storage box\")\n",
    "\n",
    "# Summary: {summary}\n",
    "objects = {objects_str}\n",
    "receptacles = {receptacles_str}\n",
    "pick_and_place(\"{first_object}\",'''\n",
    "    objects_str = '[' + ', '.join(map(lambda x: f'\"{x}\"', objects)) + ']'\n",
    "    receptacles_str = '[' + ', '.join(map(lambda x: f'\"{x}\"', receptacles)) + ']'\n",
    "    return placement_prompt_template.format(summary=summary, objects_str=objects_str, receptacles_str=receptacles_str, first_object=objects[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f622aade",
   "metadata": {},
   "outputs": [],
   "source": [
    "def evaluate(scenarios, eval_split='unseen', model='text-davinci-003', verbose=False):\n",
    "    assert eval_split in {'unseen', 'seen'}\n",
    "    completion = Completion()\n",
    "    accuracies = []\n",
    "    for i, scenario in enumerate(tqdm(scenarios)):\n",
    "        if verbose:\n",
    "            print(f'Scenario {i + 1} of {len(scenarios)}\\n')\n",
    "\n",
    "        # Object placement\n",
    "        objects = scenario.seen_objects if eval_split == 'seen' else scenario.unseen_objects\n",
    "        placement_prompt = construct_placement_prompt(scenario.annotator_notes, objects, scenario.receptacles)\n",
    "        placement_completion = completion.create(placement_prompt, model)['choices'][0]['text']\n",
    "        if verbose:\n",
    "            print(placement_prompt, end='')\n",
    "            utils.print_colored(placement_completion, 'blue')\n",
    "            print('\\n' + 10 * '-' + '\\n')\n",
    "\n",
    "        # Analysis\n",
    "        predicted_placements = benchmark.parse_placements(placement_completion, objects)\n",
    "        correct_placements = scenario.seen_placements if eval_split == 'seen' else scenario.unseen_placements\n",
    "        corrects, accuracy = benchmark.check_placements(predicted_placements, correct_placements)\n",
    "        accuracies.append(accuracy)\n",
    "        if verbose:\n",
    "            print(f'Annotator notes: {scenario.annotator_notes}\\n')\n",
    "            print('Correct placements:')\n",
    "            for placement in correct_placements:\n",
    "                print(placement)\n",
    "            print('\\nParsed placements:')\n",
    "            for placement, correct in zip(predicted_placements, corrects):\n",
    "                utils.print_colored(placement, 'green' if correct else 'red')\n",
    "            print(f'\\nAccuracy: {accuracy:.2f}')\n",
    "            print('\\n' + 80 * '-' + '\\n')\n",
    "    return accuracies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8bcd7db",
   "metadata": {},
   "outputs": [],
   "source": [
    "scenarios = benchmark.load_scenarios()\n",
    "len(scenarios)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9057ecb4",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#accuracies = evaluate(scenarios, 'unseen', verbose=True)\n",
    "accuracies = evaluate(scenarios, 'unseen')\n",
    "np.mean(accuracies).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1da4f65d",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "#accuracies = evaluate(scenarios, 'seen', verbose=True)\n",
    "accuracies = evaluate(scenarios, 'seen')\n",
    "np.mean(accuracies).round(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "394c6867",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
